<template>
    <div style="width:100%; height: 100%;" ref="myChartRef"></div>
</template>

<script setup lang="ts">
import { onMounted, onUnmounted, toRefs, ref, watch, markRaw } from "vue";
import * as echarts from "echarts";
//   import EventBus from "@/events";

type EchartsProp = {
    options: {
        [key: string]: any;
    };
    needListen?: boolean;
};

const props = withDefaults(defineProps<EchartsProp>(), {
    needListen: false,
});

const { options } = toRefs(props);

const myChartRef = ref<any>();
// const chartInstance = ref<any>();
let chartInstance: any = null;

const init = () => {
    chartInstance = markRaw(echarts.init(myChartRef.value));
    chartInstance.setOption(options?.value);

    observer();
};

const updateOptions = (options: any) => {
    chartInstance.dispose();
    chartInstance = markRaw(echarts.init(myChartRef.value));
    chartInstance.setOption(options);
    observer();
};

/**
 * @监听事件
 */
  const observer = () => {
    if (props.needListen) {
      chartInstance.on("click", (params: any) => {
        // EventBus.emit("chartClick", params);
        console.log('监听了点击事件');
        
      });
    }
  };

watch(
    () => options.value,
    (newOptions) => {
        updateOptions(newOptions);
    },
    { deep: true }
);

onMounted(() => {
    init();
});

onUnmounted(() => {
    if (props.needListen) {
        chartInstance.dispose();
    }
});
</script>

<style lang="scss" scoped></style>